<?php

/**
 * Mapper for {@link Content} from array.
 * @see ContentValidator
 */
final class ContentMapper {

    private function __construct() {
        
    }

    /**
     * Maps array to the given {@link Content}.
     * <p>
     * Expected properties are:
     * <ul>
     *   <li>id</li>
     *   <li>date</li>
     *   <li>title</li>
     *   <li>text</li>
     *   <li>valid</li>
     *   <li>category_id</li>
     *   <li>grades_number</li>
     *   <li>grades_total</li>
     *   <li>user_ip</li>
     *   <li>last_modified_on</li>
     * </ul>
     * @param Content $content
     * @param array $properties
     */
    public static function map(Content $content, array $properties) {
        if (array_key_exists('id', $properties)) {
            $content->setId($properties['id']);
        }
        if (array_key_exists('date', $properties)) {
            $lastModifiedOn = self::createDateTime($properties['date']);
            if ($lastModifiedOn) {
                $content->setDate($lastModifiedOn);
            }
        }
        if (array_key_exists('title', $properties)) {
            $content->setTitle(trim($properties['title']));
        }
        if (array_key_exists('text', $properties)) {
            $content->setText(trim($properties['text']));
        }
        if (array_key_exists('valid', $properties)) {
            $content->setValid(trim($properties['valid']));
        }
        if (array_key_exists('category_id', $properties)) {
            $content->setCategoryId(trim($properties['category_id']));
        }
        if (array_key_exists('grades_number', $properties)) {
            $content->setGradesNumber($properties['grades_number']);
        }
        if (array_key_exists('grades_total', $properties)) {
            $content->setGradesTotal($properties['grades_total']);
        }
        if (array_key_exists('user_ip', $properties)) { 
            $content->setUserIp(trim($properties['user_ip']));
        }
        if (array_key_exists('last_modified_on', $properties)) {
            $lastModifiedOn = self::createDateTime($properties['last_modified_on']);
            if ($lastModifiedOn) {
                $content->setLastModifiedOn($lastModifiedOn);
            }
        }
    }

    private static function createDateTime($input) {
        return DateTime::createFromFormat('Y-n-j H:i:s', $input);
    }

}

?>
